package demo.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import util.JsonUtil;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapDecoder extends MessageToMessageDecoder<ByteBuf> {
    // TODO Use CharsetEncoder instead.
    private final Charset charset;

    /**
     * Creates a new instance with the current system character set.
     */
    public MapDecoder() {
        charset = Charset.defaultCharset();
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//        Object decoded = decode(ctx, in);
//        if (decoded != null) {
//            out.add(decoded);
//        }
//        byte[] arr = new byte[in.readableBytes()];
//        in.writeBytes(arr);
//        String s = new String(arr, charset);
        String s = in.toString(charset);
        Map<String, String> map = JsonUtil.jsonToBean(s, HashMap.class);
//        System.out.println(s);
        out.add(map);

    }
}
